#!/bin/env python
#-*- encoding:utf-8 -*-
import urllib,urllib2,os
import json
import time,sys
import hashlib
import socket
import telIds
import time
import platform
'''
已完成 从ICS3.0后台提取本教学点所需的题库试题ID，并最终输出  题库所需的md5加密值和试题id
'''
class httpAccess(object):

    def __init__(self):
        pass

    def getRes(self,telId='',md5='',plat='',sys='',key='',type='0'):
        try:
            #uri       = 'http://10.1.250.71:8080/icsinterface/rest/curriculum/queryCacheList'
            #query     = 'teachingSchool=' + telId + '&type=' + type
            #uri       = 'http://115.182.69.75:8080/icsinterface/rest/curriculum/queryCacheAndQuesByHostName'
            uri       = 'http://icsinterface.speiyou.com/icsinterface/rest/curriculum/queryCacheAndQuesByHostName'
            #query     = 'school=' + telId
            query     = 'hostName=' + telId
            url       = uri + '?' + query
            headers   ={ 'User-Agent' : 'Cache Squid python', 'Accept' : '*/*', 'Content-type':'text/plain', 'plat':plat, 'sys':sys, 'md5':md5, 'key':key}
            req       = urllib2.Request(url,headers=headers)
            response  = urllib2.urlopen(req)
            the_page  = response.read()
            return the_page
        except Exception,n:
            srvname = str(socket.gethostname())
            runTime   = time.strftime('%Y%m%d_%H',time.localtime(time.time()))
            writeFile(srvname,runTime,'log','error','connect icsinterface service Error!' + str(n))

def mkMd5Str(uname='',upwd='',Ukey='', telId='', Plat='',Sys='',ids='',Skey=''):
    Str     = uname + upwd + Ukey + telId + Plat + Sys + ids + Skey
    md5Str  = hashlib.md5(Str.encode('utf-8')).hexdigest()
    doneStr = md5Str + ' ' + ids
    return md5Str,telId,doneStr

def jsonToDic(jsonObj):
    if platform.python_version() == '2.4.3':
        jsonDic   = json.read(jsonObj)
    if platform.python_version() == '2.6.6':
        jsonDic   = json.loads(jsonObj)
    return jsonDic

def getResPath(SerRes):
    questionsIds = SerRes['result']['questions']
    staticPath = SerRes['result']['coursewares']
    return questionsIds,staticPath

def getQueIds(SerRes):
    QueIds = SerRes['result']['questionData']
    return QueIds

'''
def writeFile(srvname,runTime,dir,msgType,msg):
    Path = '/tmp/' + msgType + '/' + dir
    if not (os.path.isdir(Path)):
        os.mkdir(Path)
    try:
        fileHandle = open('/tmp/' + msgType + '/' + dir + '/' + srvname + '_' + msgType + '_' + runTime,'a')
        for i in msg:
            fileHandle.write(i + '\n')
        #fileHandle.save()
        fileHandle.flush()
        fileHandle.close()
    except Exception,e:
        srvname = socket.gethostname()
        runTime   = time.strftime('%Y%m%d_%H',time.localtime(time.time()))
        writeFile(srvname,runTime,'log','error',e)
'''

def structure(path):
    resList = list()
    pathList = path.split('/')
    for  i in pathList:
        if i:
            resList.append(i)
    return resList

def writeFile(srvname,runTime,dir,msgType,msg):
    Path = '/tmp/' + msgType + '/' + dir
    dirPath = structure(Path)
    dirMk = str()
    for i in dirPath:
        dirMk = dirMk + '/' + i 
        if not (os.path.isdir(dirMk)):
            os.mkdir(dirMk)
    try:
        fileHandle = open('/tmp/' + msgType + '/' + dir + '/' + srvname + '_' + msgType + '_' + runTime,'a')
        if msgType == 'error':
            fileHandle.write(msg + '\n')
            fileHandle.flush()
            fileHandle.close()
        else:
            for i in msg:
                fileHandle.write(i + '\n')
            #fileHandle.save()
            fileHandle.flush()
            fileHandle.close()
    except Exception,e:
        srvname = socket.gethostname()
        runTime   = time.strftime('%Y%m%d_%H',time.localtime(time.time()))
        writeFile(srvname,runTime,'log','error',str(e))

def main():
    #srvname = socket.gethostname()
    #srvname = 'bj_gzfqyw_yqw_ics3.0'
    srvname = '10016_bj_hdhz1_ics3'
    print "srvname=", srvname
    '''telIds = list()'''
    plat      = 'squid'
    sysplat   = 'speiyou'
    skey      = 'com.xes.itempool'
    runTime   = time.strftime('%Y%m%d_%H%M',time.localtime(time.time()))
    httpobj = httpAccess()
    telList = telIds.Ids(srvname)
    #telList = ['855A68A60B2942B3934340F5435B96CE']
    print "telList=", telList
    for j in telList:
        print '---------------------->>' + j + '<<   start' + '----------------------------------'
        md5, ids, md5Andids = mkMd5Str(Plat=plat,Sys=sysplat,telId=j,Skey=skey)
        print 'md5:' + md5 + '\n' + 'Telids:' + ids
        res = httpobj.getRes(telId=ids,md5=md5,plat=plat,sys=sysplat,key=skey)
        resDic = jsonToDic(res)
        print "response_json=", resDic
        '''
        resDic = {
            'result': {
                'msg': 'ok',
                'rlt': 'True',
                'coursewares': [
                    'http://10.1.250.71:8080/ICSmananger/upload/coursewaresource/11401339779640/lecture.ics',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/5938d678-facb-45b9-9d40-700368f472e3.mp4',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/5938d678-facb-45b9-9d40-700368f472e3.jpg',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/85de8341-4d70-4230-8923-0e36fded2414.mp4',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/85de8341-4d70-4230-8923-0e36fded2414.jpg',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/9d0a0ab3-2310-436d-9061-56656f63e0b6.mp4',
                    'http://10.1.250.71:8080/ICSmananger/upload/videos/9d0a0ab3-2310-436d-9061-56656f63e0b6.jpg'
                ],
                'questions': [
                    '07fea5cdead4426597e75f4b2d086bbb',
                    '3a7be5aa75eb415e8c1587085a4c6e5d',
                    '4d04a01e598749d6bec8eb3846db79c1',
                    '5e79aae3fe704e16b0193ca793123599'
                ]
            }
        }
        '''
        if (resDic['result'].has_key('questions') or resDic['result'].has_key('coursewares')):
            questionsIds,staticPath = getResPath(resDic)
            writeFile(srvname,runTime,'queue','questions',questionsIds)
            writeFile(srvname,runTime,'queue','static',staticPath)
            print 'questionsIds: %s \n' % (questionsIds)
            print type(questionsIds)
            print 'staticPath: %s' % (staticPath)
            print type(staticPath)
            for i in questionsIds:
                print mkMd5Str(Plat=plat,Sys=sysplat,ids=str(i),Skey=skey)[2]
        else:
            #os.exit()
            pass
        print '--------------------->>' + j + '<<    end' + '-----------------------------------\n\n'


if __name__ == '__main__':
    main()
